package com.lottery.bootdo.common.controller.member;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lottery.bootdo.common.domain.DictDO;
import com.lottery.bootdo.common.service.MemberInfoService;
import com.lottery.bootdo.common.utils.PageUtils;
import com.lottery.bootdo.common.utils.ShiroUtils;
import com.lottery.bootdo.common.utils.StringUtils;
import com.lottery.bootdo.system.domain.UserDO;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.entity.CustomInfo;
import com.lottery.common.entity.EventsInfo;
import com.lottery.common.entity.MemberCertify;
import com.lottery.common.entity.MemberInfo;
import com.lottery.common.service.DecryptToObjectService;
import com.lottery.common.service.FileUploadService;
import com.lottery.common.service.MemberCertifyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.lottery.common.contants.Constants.*;

/**
 * @author o551wwl
 */
@Controller
@RequestMapping("/member")
@Slf4j
@Api(value = "/member",tags="会员操作类")
public class MemberInfoController {
	private ReQueryResult result = new ReQueryResult();
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	@Value("${appTemplateCode}")
	private String templateCode;
	@Value("${base.upload.path}")
	private String uploadPath;
	@Autowired
	private DecryptToObjectService decryptToObjectService;
	@Resource
	private MemberInfoService memberInfoService;
	@Autowired
	private MemberCertifyService memberCertifyService;
	@Autowired
	private FileUploadService fileUploadService;

	@RequiresPermissions("member:list")
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	String index() {
		return "common/member/index";
	}

	@RequiresPermissions("member:certify:list")
	@RequestMapping(value = "/toCertify", method = RequestMethod.GET)
	String certify() {
		return "common/member/certify/index";
	}


	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	@RequiresPermissions("member:detail")
	String detail( @PathVariable() Long id, Model model) {
		MemberInfo info=memberInfoService.getById(id);
		model.addAttribute("info", info);
		return "common/member/detail";
	}


	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@RequiresPermissions("member:edit")
	String edit( @PathVariable() Long id, Model model) {
		MemberInfo info=memberInfoService.getById(id);
		if (info==null){
			info=new MemberInfo();
		}
		model.addAttribute("info", info);
		return "common/member/edit";
	}


	@ApiOperation(value = "列表查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name",value = "姓名",dataType="file"),
			@ApiImplicitParam(name = "phone",value = "号码",dataType="String")
	})
	@RequestMapping(value = "", method = RequestMethod.GET)
	@RequiresPermissions(value={"member:list"})
	@ResponseBody
	public PageUtils memberAll(String json){
		result = new ReQueryResult();
		NutMap nutMap=decryptToObjectService.jsonToObject(json,NutMap.class);

		log.info("numap is {}",JSON.toJSONString(nutMap));
//		Page<MemberInfo> page = new Page<>(nutMap.getInt("pageIndex"),nutMap.getInt("pageLength"));
//		IPage<MemberInfo> records=memberInfoService.getMemberList(page,nutMap);

		QueryWrapper<MemberInfo> queryWrapper=new QueryWrapper<>();
		queryWrapper.in("status","0","1");
		if(StringUtils.isNotBlank(nutMap.getString("isExpired"))){
			if (nutMap.getInt("isExpired")==0) {
				queryWrapper.apply("  expired_time > curdate()");
			} else {
				queryWrapper.apply("   (expired_time <= curdate() or expired_time is null)");
			}
		}
		if (StringUtils.isNotBlank(nutMap.getString("startTime"))){
			queryWrapper.apply("  create_time > '"+nutMap.getString("startTime")+"'");
		}
		if (StringUtils.isNotBlank(nutMap.getString("endTime"))){
			queryWrapper.apply("  create_time < '"+nutMap.getString("endTime")+"'");
		}
		if (StringUtils.isNotBlank(nutMap.getString("phone"))){
			queryWrapper.eq("phone",nutMap.getString("phone"));
		}
		if (StringUtils.isNotBlank(nutMap.getString("id"))){
			queryWrapper.eq("id",nutMap.getString("id"));
		}
		if (StringUtils.isNotBlank(nutMap.getString("isCertify"))){
			if (nutMap.getString("isCertify").equals("0"))
				queryWrapper.eq("is_certify",TYPE_ZERO);
			if (!nutMap.getString("isCertify").equals("0"))
				queryWrapper.in("is_certify",TYPE_ONE,TYPE_TWO,TYPE_THREE);
		}
		Page<MemberInfo> page = new Page<>(nutMap.getInt("pageIndex"),nutMap.getInt("pageLength"));

		IPage<MemberInfo> records=memberInfoService.page(page,queryWrapper);
		log.info(JSON.toJSONString(records));
//
        PageUtils pageUtils = new PageUtils(records.getRecords(),new BigDecimal(records.getTotal()).intValue());
        return pageUtils;
	}

	/**
	 * 详情查询
	 * @param id  文章ID
	 * @return
	 */
	@ApiOperation(value = "详情查询")
	@ApiImplicitParam(name = "id",value = "文章ID",dataType="Integer")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@RequiresPermissions(value={"member:list"})
	@ResponseBody
	public ReQueryResult memberDetail(@PathVariable Long id){
		result = new ReQueryResult();
		MemberInfo info=memberInfoService.getById(id);
		result.setData(info);
		result.success(SUCCESS_DESC);
		return result;
	}


	@ApiOperation(value = "修改会员")
	@ApiImplicitParam(name = "json",value = "MemberInfo 对象str",dataType="String")
	@RequestMapping(value = "", method = RequestMethod.PUT)
	@RequiresPermissions(value={"member:edit"})
	@ResponseBody
	public ReQueryResult editMember(String json){
		result = new ReQueryResult();
		MemberInfo info=new MemberInfo();
		try {
			info= decryptToObjectService.jsonToObject(json,MemberInfo.class);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(ExceptionUtils.getFullStackTrace(e));
			result.error(RSA_ERROR_DESC);
			return result;
		}
		memberInfoService.saveOrUpdate(info);
		result.success(SUCCESS_DESC);
		return result;
	}

	@ApiOperation(value = "删除用户")
	@ApiImplicitParam(name = "id",value = "文章ID",dataType="Integer")
	@RequestMapping(value = "", method = RequestMethod.DELETE)
	@RequiresPermissions(value={"member:del"})
	@ResponseBody
	public ReQueryResult delete( MemberInfo info){
		result = new ReQueryResult();

		info.setStatus(TYPE_ONE);
		memberInfoService.updateById(info);
		result.success(SUCCESS_DESC);
		return result;
	}


	@ApiOperation(value = "删除用户")
	@ApiImplicitParam(name = "id",value = "文章ID",dataType="Integer")
	@RequestMapping(value = "/batchRemove", method = RequestMethod.DELETE)
	@RequiresPermissions(value={"member:del"})
	@ResponseBody
	public ReQueryResult batchRemove(@RequestParam("ids[]") Long[] ids){
		result = new ReQueryResult();
		List<MemberInfo> list=new ArrayList<>();
		MemberInfo info;
		for (Long id:ids){
			info=new MemberInfo();
			info.setId(id);
			info.setStatus(TYPE_ONE);
			list.add(info);
		}
		memberInfoService.updateBatchById(list);
		result.success(SUCCESS_DESC);
		return result;
	}



	@ApiOperation(value = "列表查询")
	@RequestMapping(value = "/certify", method = RequestMethod.GET)
	@RequiresPermissions(value={"member:certify:list"})
	@ResponseBody
	public PageUtils memberCertify(String json){
		result = new ReQueryResult();
		NutMap nutMap=decryptToObjectService.jsonToObject(json,NutMap.class);
		log.info("numap is {}",JSON.toJSONString(nutMap));
		QueryWrapper<MemberCertify> queryWrapper=new QueryWrapper<>();
		if (StringUtils.isNotBlank(nutMap.getString("phone"))){
			queryWrapper.eq("phone",nutMap.getString("phone"));
		}
		if (StringUtils.isNotBlank(nutMap.getString("id"))){
			queryWrapper.eq("id",nutMap.getString("id"));
		}
		if (StringUtils.isNotBlank(nutMap.getString("isCertify"))){
			queryWrapper.eq("status",nutMap.getString("isCertify"));
		}
//		if (StringUtils.isNotBlank(nutMap.getString("isCertify"))){
//			if (nutMap.getString("isCertify").equals("0"))
//				queryWrapper.eq("is_certify",TYPE_ZERO);
//			if (!nutMap.getString("isCertify").equals("0"))
//				queryWrapper.in("is_certify",TYPE_ONE,TYPE_TWO,TYPE_THREE);
//		}
		Page<MemberCertify> page = new Page<>(nutMap.getInt("pageIndex"),nutMap.getInt("pageLength"));

		IPage<MemberCertify> records=memberCertifyService.page(page,queryWrapper);
		log.info(JSON.toJSONString(records));
		PageUtils pageUtils = new PageUtils(records.getRecords(),new BigDecimal(records.getTotal()).intValue());
		return pageUtils;
	}

	@ApiOperation(value = "修改会员")
	@RequestMapping(value = "/certify", method = RequestMethod.PUT)
	@RequiresPermissions(value={"member:certify:edit"})
	@ResponseBody
	public ReQueryResult editCertify(MemberCertify certify){
		result = new ReQueryResult();
		UserDO userDO= ShiroUtils.getUser();
//		MemberCertify certify=new MemberCertify();
//		try {
//			certify= decryptToObjectService.jsonToObject(json,MemberCertify.class);
//		} catch (Exception e) {
//			e.printStackTrace();
//			log.error(ExceptionUtils.getFullStackTrace(e));
//			result.error(RSA_ERROR_DESC);
//			return result;
//		}
		certify.setOperationId(userDO.getUserId());
		certify.setOperationName(userDO.getUsername());
		certify.setOperationTime(new Date());
		memberCertifyService.updateById(certify);
		MemberInfo memberInfo=new MemberInfo();
		memberInfo.setId(certify.getMemberId());
		memberInfo.setIsCertify(certify.getStatus());
		memberInfoService.updateById(memberInfo);
		result.success(SUCCESS_DESC);
		return result;
	}


	@ApiOperation(value = "阿里oss临时凭证")
	@RequestMapping(value = "/sts", method = RequestMethod.GET)
	@ResponseBody
	public ReQueryResult STSAssumeRoleAccess(){
		log.info("阿里oss临时凭证");
		result=new ReQueryResult();
		result=fileUploadService.getSTSToken();
		log.info("result is {}",JSON.toJSONString(result));
		return  result;
	}


}
